package com.oocl.servlet;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.oocl.pojo.Customer;
import com.oocl.pojo.Favorite;
import com.oocl.service.CustomerService;
import com.oocl.service.impl.CustomerServiceImpl;

/**
 * Servlet implementation class AddCustomerServlet
 */
public class AddCustomerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private CustomerService service;
    /**
     * Default constructor. 
     */
    public AddCustomerServlet() {
    	service = new CustomerServiceImpl();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//接参
		String cname = request.getParameter("name");
		String csal = request.getParameter("sal");
		String csex = request.getParameter("sex");
		String cbirth = request.getParameter("birth");
		String[] cfavs = request.getParameterValues("favs");
		//校验
		if(!service.verifyNameFormat(cname)){
			response.sendRedirect("error.jsp");
			return;
		}

		//类型转换
		
		List<Favorite> favs = new ArrayList<Favorite>();
		for(int i=0; i<cfavs.length; i++){
			favs.add(new Favorite(i, cfavs[i].replace("/", "")));
		}
		boolean sex = Boolean.parseBoolean(csex);
		double sal = Double.parseDouble(csal);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date birth = null;
		try {
			birth = sdf.parse(cbirth);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		//封装
		Customer c = new Customer(null, cname, sal, sex, birth, favs);
		System.out.println("插入数据库之前 "+c.toString());
		//调用业务
		int m = service.addCustomer(c);
		if(m > 0){
			
			HttpSession sen = request.getSession();
			
			
			sen.setAttribute("customers", service.findAllCustomers());
//			request.getRequestDispatcher("/list.jsp").forward(request, response);
			response.sendRedirect("list.jsp");
			System.out.println("已经发送到所有页面");
		}else{
			request.getRequestDispatcher("/error.jsp").forward(request, response);
		}
	}

}
